//
//  WPViewModel.m
//  wobingwoyi
//
//  Created by WGP on 16/8/26.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPViewModel.h"

@interface WPViewModel ()

@property(nonatomic,assign)BOOL isLoadingStatus;

@end
@implementation WPViewModel

+(instancetype)sharedInstance
{
    static WPViewModel *instance  = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc] init];
    });
    return instance;
}

-(void)loadDataWithURL:(NSString *)url parameters:(id)parameters finished:(void(^)(NSArray *dictsArr, NSError *error))finishedBlock
{
    if (self.isLoadingStatus)
    {
//        WPLog(@"已经有加载任务了");
        return ;
    }
    self.isLoadingStatus = YES;
    
    [[WPNetWorkManager sharedNetWorkManager]  POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.isLoadingStatus = NO;
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            finishedBlock(responseDict[@"detail"],nil);
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }
            
            finishedBlock(nil,nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
         self.isLoadingStatus = NO;
        [self showErrorInfoWithStatus:@"网络错误"];
        finishedBlock(nil,error);
        
    }];
}

@end
